//
//  BDHomeViewController.m
//  BeidouMall
//
//  Created by qie on 16/3/28.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDHomeViewController.h"
#import "BDScanViewController.h"
#import "SDCycleScrollView.h"
#import "BDNavigationBarView.h"
#import "BDSearchViewController.h"
#import "BDGoodDetailViewController.h"
#import "BDNavigationController.h"
#import "BDTypeViewController.h"
#import "BDBeidouViewController.h"
#import "BDLoginTableViewController.h"
#import "BDGanziHomeViewController.h"
#import "BDMinmaoHomeViewController.h"
#import "BDSelfSupportHomeViewController.h"

#define firstHeightWidthRatio 1.8
#define fourHeightWidthRatio 1.189 // 88 : 74 96 : 93
#define hotHeightWidthRatio 0.926// 100 : 108
#define kPageSize 9

@interface BDHomeViewController () <UITabBarControllerDelegate,
                                    UITableViewDelegate,
                                    UITableViewDataSource,
                                    UICollectionViewDelegate,
                                    UICollectionViewDataSource,
                                    SDCycleScrollViewDelegate,
                                    BDNavigationBarViewDelegate,
                                    UITextFieldDelegate>
{
    NSInteger _curPage;
    NSArray *_firstList;// 滑动广告列表
    NSArray *_secondList;// 热门商品列表
    NSMutableArray *_thirdList;// 推荐商品列表
    UIImageView *_navBarHairlineImageView;// 原生导航栏上的黑线,原来的自定义导航栏需要全透明所以原生的那条黑线需要隐藏，现在无所谓
    BDNavigationBarView *_navgationBarView;
    
    CGFloat _recomHeightWidthRatio;// 推荐商品cell高宽比例
    NSUInteger _selectControllerIndex;// tabbar选中index
    NSString *_appID;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation BDHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tabBarController.delegate = self;
    
    // 处理tableView上面多出来20个像素(是因为自动布局的缘故)
    self.edgesForExtendedLayout = UIRectEdgeNone;
    // 自定义tableview刷新的头部和尾部
    [self setTableViewHeader];
    [self setTableViewFooter];
    _thirdList = [[NSMutableArray alloc] init];
    [_tableView.mj_header beginRefreshing];
    _curPage = 0;
    
//    [self checkUpdate];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 设置状态栏样式 白色字
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];//UIStatusBarStyleDefault
    
    if ([[BDAccountManagerModel shareInstance].payResult isEqualToString:@"selectTabBar"]) {// 当支付完成(成功或失败)跳回到根页面后要选择到我的这一项
        self.tabBarController.selectedIndex = 4;
    }
    
    [self hideNavgationBarBlackLine];
    
    // nav_bg2一个透明的图片替换原来的nav_bg 隐藏原生导航栏
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bg2"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.translucent = YES;
    
    _navgationBarView = [[NSBundle mainBundle] loadNibNamed:@"BDNavgationBarView" owner:nil options:nil].firstObject;
    _navgationBarView.frame = CGRectMake(0, 0.0, kScreen_Width, 64.0);
    _navgationBarView.delegate = self;
    _navgationBarView.textField.delegate = self;
    _navgationBarView.tag = 998;
    if (![[BDAccountManagerModel shareInstance].langage isEqualToString:@"zh"]) {
        _navgationBarView.promitLabel.font = [UIFont systemFontOfSize:12.0];
    }
    [self.navigationController.view addSubview:_navgationBarView];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 设置状态栏样式 黑色字
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];//UIStatusBarStyleDefault
    _navBarHairlineImageView.hidden = NO;
    if ([_navgationBarView.textField isFirstResponder]) {
        [_navgationBarView.textField resignFirstResponder];
    }
    if (_navgationBarView) {
        dispatch_async(dispatch_get_main_queue(), ^{
             [_navgationBarView removeFromSuperview];
        });
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - Private method

- (void)reloadData:(id) sender {
    _curPage = 1;
    // FIRST_LEVEL 首页最上栏
    NSString *url1 = [NSString stringWithFormat:@"%@%@?currentPage=%d&pageSize=%d&hotType=%@",
                     [BDNetworking shareInstance].baseUrl,
                     Good_Query,
                     1,
                     20,
                     @"FIRST_LEVEL"];
    [[BDNetworking shareInstance] postWithUrl:url1 sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([_tableView.mj_header isRefreshing]) {
                [_tableView.mj_header endRefreshing];
            }
        });
        if (error) {
            NSLog(@"获取首页FIRST_LEVEL失败 %@",error);
        } else {
            NSLog(@"FIRST_LEVEL results = %@",results);
            NSDictionary *resultDic = (NSDictionary *)results;
            _firstList = resultDic[@"objects"];
            dispatch_async(dispatch_get_main_queue(), ^{
                NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
                [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            });
        }
    }];
    // SECOND_LEVEL 首页抢购商品栏
    NSString *url2 = [NSString stringWithFormat:@"%@%@?currentPage=%d&pageSize=%d&hotType=%@",
                     [BDNetworking shareInstance].baseUrl,
                     Good_Query,
                     1,
                     20,
                     @"SECOND_LEVEL"];
    [[BDNetworking shareInstance] postWithUrl:url2 sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([_tableView.mj_header isRefreshing]) {
                [_tableView.mj_header endRefreshing];
            }
        });
        if (error) {
            NSLog(@"获取首页SECOND_LEVEL失败 %@",error);
        } else {
            NSLog(@"SECOND_LEVEL results = %@",results);
            NSDictionary *resultDic = (NSDictionary *)results;
            _secondList = resultDic[@"objects"];
            dispatch_async(dispatch_get_main_queue(), ^{
                NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:0];
                [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            });
        }
    }];
    // NORMAL 首页推荐商品
    if ([_tableView.mj_footer isRefreshing]) {
        
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{// 恢复为普通状态
            [_tableView.mj_footer resetNoMoreData];
        });
        
        NSString *url3 = [NSString stringWithFormat:@"%@%@?currentPage=%d&pageSize=%d&hotType=%@",
                          [BDNetworking shareInstance].baseUrl,
                          Good_Query,
                          1,
                          kPageSize,
                          @"NORMAL"];
        [[BDNetworking shareInstance] postWithUrl:url3 sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                _tableView.mj_footer.hidden = NO;
                if ([_tableView.mj_header isRefreshing]) {
                    [_tableView.mj_header endRefreshing];
                }
            });
            if (error) {
                NSLog(@"获取首页NORMAL失败 %@",error);
            } else {
                NSLog(@"NORMAL results = %@",results);
                NSDictionary *resultDic = (NSDictionary *)results;
                NSArray *resultList = resultDic[@"objects"];
                [_thirdList removeAllObjects];
                [_thirdList addObjectsFromArray:resultList];
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:4 inSection:0];
                    [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                });
            }
        }];
    }
}

- (void)reloadDataByFooter:(id) sender {
    if ([_tableView.mj_header isRefreshing]) {
        
    } else {
//        _tableView.mj_footer.hidden = YES;
        _curPage = _curPage + 1;
        // NORMAL 首页推荐商品
        NSString *url3 = [NSString stringWithFormat:@"%@%@?currentPage=%ld&pageSize=%d&hotType=%@",
                          [BDNetworking shareInstance].baseUrl,
                          Good_Query,
                          (long)_curPage,
                          kPageSize,
                          @"NORMAL"];
        [[BDNetworking shareInstance] postWithUrl:url3 sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([_tableView.mj_footer isRefreshing]) {
                    [_tableView.mj_footer endRefreshing];
                }
            });
            if (error) {
                NSLog(@"获取首页NORMAL失败 %@",error);
            } else {
                NSLog(@"NORMAL results = %@",results);
                NSDictionary *resultDic = (NSDictionary *)results;
                NSArray *resultList = resultDic[@"objects"];
                if ([resultList count] > 0) {
                    if ([resultList count] < kPageSize) {// 数据不够分页,显示没有更多了
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [_tableView.mj_footer endRefreshingWithNoMoreData];
                        });
                    }
                    [_thirdList addObjectsFromArray:resultList];
                    
//                    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC);
//                    dispatch_after(time, dispatch_get_main_queue(), ^{
//                        _tableView.mj_footer.hidden = NO;
//                    });
                } else {
                    if (_curPage > 1) { // 分页引起的刷新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [_tableView.mj_footer endRefreshingWithNoMoreData];
                        });
                    }
//                    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC);
//                    dispatch_after(time, dispatch_get_main_queue(), ^{
//                        _tableView.mj_footer.hidden = NO;
//                    });
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:4 inSection:0];
                    [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                });
            }
        }];
    }
}

- (void)setTableViewHeader {
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self reloadData:nil];
    }];
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        header.stateLabel.font = [UIFont fontWithName:@"Bzdbt" size:9.0];
    }
    
    [header setTitle:NSLocalizedString(@"Pull down to refresh", nil) forState:MJRefreshStateIdle];
    [header setTitle:NSLocalizedString(@"Release to refresh", nil) forState:MJRefreshStatePulling];
    [header setTitle:NSLocalizedString(@"Loading ...", nil) forState:MJRefreshStateRefreshing];
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    
    _tableView.mj_header = header;
}

- (void)setTableViewFooter {
//    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        [self reloadDataByFooter:nil];
//    }];
//    // 设置文字
//    [footer setTitle:@"" forState:MJRefreshStateIdle];// 上拉加载
//    [footer setTitle:NSLocalizedString(@"loading", nil) forState:MJRefreshStateRefreshing];
//    [footer setTitle:NSLocalizedString(@"loaded all data", nil) forState:MJRefreshStateNoMoreData];
//    _tableView.mj_footer = footer;
    
    _tableView.mj_footer = [MJDIYBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadDataByFooter:)];
}

- (void)hideNavgationBarBlackLine {
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]){
        NSArray *list=self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView=(UIImageView *)obj;
                NSArray *list2 = imageView.subviews;
                for (id obj2 in list2) {
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        UIImageView *imageView2=(UIImageView *)obj2;
                        _navBarHairlineImageView = imageView2;
                        _navBarHairlineImageView.hidden = YES;
                    }
                }
            }
        }
    }
}

- (void)checkUpdate {
    _appID = @"1104901466";
    //定义的App地址
    NSString *urlStr = [NSString stringWithFormat:@"http://itunes.apple.com/cn/lookup?id=%@",_appID];
    //AppID即是如图红色箭头获取的AppID
    //PS:有的时候可能会请求不到数据，但是AppID对了，有可能是App是上架区域范围的原因，建议使用在com末尾加上“／cn”
    //例：NSString *url = [NSString stringWithFormat:@"http://itunes.apple.com/cn/lookup?id=%@",AppID];
    
    
    //网络请求App的信息（我们取Version就够了）
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                       timeoutInterval:10];
    
    [request setHTTPMethod:@"POST"];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSMutableDictionary *receiveStatusDic=[[NSMutableDictionary alloc]init];
        if (data) {
            
            //data是有关于App所有的信息
            NSDictionary *receiveDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            if ([[receiveDic valueForKey:@"resultCount"] intValue] > 0) {
                
                [receiveStatusDic setValue:@"1" forKey:@"status"];
                [receiveStatusDic setValue:[[[receiveDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"version"]   forKey:@"version"];
                
                //请求的有数据，进行版本比较
                [self performSelectorOnMainThread:@selector(receiveData:) withObject:receiveStatusDic waitUntilDone:NO];
            }else{
                
                [receiveStatusDic setValue:@"-1" forKey:@"status"];
            }
        }else{
            [receiveStatusDic setValue:@"-1" forKey:@"status"];
        }
        
    }];
    
    [task resume];

}

-(void)receiveData:(id)sender
{
    //获取APP自身版本号
    NSString *localVersion = [[[NSBundle mainBundle]infoDictionary]objectForKey:@"CFBundleShortVersionString"];
    NSString *appStoreVersion = sender[@"version"];
    //当前AppStore版大于本地版本
    if ([appStoreVersion compare:localVersion options:NSNumericSearch] != NSOrderedAscending && ![appStoreVersion isEqualToString:localVersion])
    {
        NSString *msg = [NSString stringWithFormat:@"你当前的版本是V%@，发现新版本V%@，是否下载新版本？",localVersion,sender[@"version"]];
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"升级提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
        
        // Create the actions.
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"下次再说" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"现在升级"style:UIAlertActionStyleDestructive handler:^(UIAlertAction*action) {
            
            //本地跳转
            NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/us/app/bei-dou/id1104901466?l=zh&ls=1&mt=8"];
            [[UIApplication sharedApplication] openURL:url];
        }];
        
        // Add the actions.
        [alertController addAction:cancelAction];
        [alertController addAction:otherAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }
}

#pragma mark BDNavigationBarViewDelegate

- (void)scanMethod {
    [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Still in process", nil)];
    
    JumpToBizProfileReq *req = [[JumpToBizProfileReq alloc]init];
    req.username=@"gh_35a336f2a7b5";
    req.extMsg = @"";
    req.profileType =0;
    [WXApi sendReq:req];
//    NSLog(@"扫码");
//    [self.navigationController pushViewController:[[BDScanViewController alloc] init] animated:YES];
}

- (void)msgMethod {
    [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Still in process", nil)];
//    NSLog(@"消息");
}

#pragma mark tableView dataSrouce

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        static NSString *cellStr = @"homePageCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        if ([cell viewWithTag:101] && _firstList.count > 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                SDCycleScrollView *cycleScrollView = (SDCycleScrollView *)[cell viewWithTag:101];
                NSMutableArray *imagesURLStrings = [NSMutableArray array];
                for (NSDictionary *goodDic in _firstList) {
                    NSString *icon = goodDic[@"icon"];
                    if (![icon isEqual:[NSNull null]] &&
                        icon != nil) {
                        [imagesURLStrings addObject:icon];
                    }
                }
                cycleScrollView.imageURLStringsGroup = imagesURLStrings;
                cycleScrollView.autoScrollTimeInterval = 3.0;
            });
            
        } else if (cell.contentView.subviews.count == 1 && _firstList.count > 0) {// 第一次加载
            dispatch_async(dispatch_get_main_queue(), ^{
                NSMutableArray *imagesURLStrings = [NSMutableArray array];
                NSMutableArray *goodNames = [NSMutableArray array];
                for (NSDictionary *goodDic in _firstList) {
                    NSString *icon = goodDic[@"icon"];
                    if (![icon isEqual:[NSNull null]] &&
                        icon != nil) {
                        [imagesURLStrings addObject:icon];
                    }
                    NSString *name = goodDic[@"name"];
                    if (![name isEqual:[NSNull null]] &&
                        name != nil) {
                        [goodNames addObject:name];
                    }
                }
                SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Width / 1.8) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
                cycleScrollView.showTitle = YES;
                cycleScrollView.namesGroup = goodNames;
                cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
                cycleScrollView.currentPageDotColor = [UIColor orangeColor]; // 自定义分页控件小圆标颜色
                cycleScrollView.pageDotColor = RGBColor(210, 210, 210);
                cycleScrollView.imageURLStringsGroup = imagesURLStrings;
                cycleScrollView.tag = 101;
                [cell addSubview:cycleScrollView];
            });
        }

        return cell;
    } else if (indexPath.row == 1) {
        static NSString *cellStr = @"homeClassCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        
        // 背兜喇叭样式
        UIView *whiteContainView = [cell viewWithTag:102];
        UILabel *notifyLabel = [whiteContainView viewWithTag:203];
        if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"en"] && kScreen_Width <= 320.0) {
            notifyLabel.font = [UIFont systemFontOfSize:9.0];
        }
        if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
            if (kScreen_Width <= 320.0) {
                notifyLabel.font = [UIFont fontWithName:@"Bzdbt" size:5.0];
            } else {
                notifyLabel.font = [UIFont fontWithName:@"Bzdbt" size:6.0];
            }
        }
        
        return cell;
    } else if (indexPath.row == 2) {
        static NSString *cellStr = @"homeShopCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        
        return cell;
    } else if (indexPath.row == 3) {
        static NSString *cellStr = @"homeHotCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        UICollectionView *collectionView = (UICollectionView *)[cell viewWithTag:902];
        [collectionView reloadData];
        
        return cell;
    } else {
        static NSString *cellStr = @"homeRecomCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        
        UICollectionView *collectionView = (UICollectionView *)[cell viewWithTag:903];
        [collectionView reloadData];
        
        return cell;
    }
}

#pragma mark tableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width,height;
    if (indexPath.row == 0) {
        return kScreen_Width / firstHeightWidthRatio;
    } else if (indexPath.row == 1) {
        CGFloat cellWidth = kScreen_Width / 5;
        return cellWidth * fourHeightWidthRatio + 41.0;// 背兜喇叭
    } else if (indexPath.row == 2) {
        if (kScreen_Width <= 320.0) {
            return 110.0;
        } else if (kScreen_Width > 320.0 && kScreen_Width <= 375.0) {
            return 128.0;
        } else {
            return 138.0;
        }
    } else if (indexPath.row == 3) {
        width = ([UIScreen mainScreen].bounds.size.width) / 3.5;
        height = width * hotHeightWidthRatio;
        return height + 25.0 + 5.0;// 上下灰色间距 不加上5.0回报cell高度比collection高的警告
    }  else if (indexPath.row == 4) {
        width = ([UIScreen mainScreen].bounds.size.width - 16.0 - 12.0) / 3;
        if (kScreen_Width <= 320.0) {
            _recomHeightWidthRatio = 1.3675;
        } else if (kScreen_Width > 320.0 && kScreen_Width <= 375.0) {
            _recomHeightWidthRatio = 1.3675;
        } else {
            _recomHeightWidthRatio = 1.3675;
        }
        height = width * _recomHeightWidthRatio;
        if (_thirdList.count > 0) {
            NSInteger count = 0;
            if (_thirdList.count % 3 != 0) {
                count = 1;
            }
            count = count + _thirdList.count / 3;
            return height * count + 30.0;
        }
        return height + 30.0;// 30.0 推荐商品标签高度
    }
    return 0.0;
}

#pragma mark - UITextField delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"SecondStoryboard" bundle:[NSBundle mainBundle]];
    BDSearchViewController *searchVC = [stroyboard instantiateViewControllerWithIdentifier:@"searchStoryboardID"];
    searchVC.searchType = YES;
    [self.navigationController pushViewController:searchVC animated:YES];
    
    return NO;// 是否循序文本字段开始编辑
}

#pragma mark - UIScrollView delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableView) {
        
    }
}

#pragma mark - colletionView delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView.tag == 901) {
        return 5;
    } else if (collectionView.tag == 902) {
        if (_secondList.count == 0) {
            return 3;
        }
        return _secondList.count;
    } else if (collectionView.tag == 903) {
        if (_thirdList.count > 0) {
            return _thirdList.count;
        }
        return 0;
    }
    return 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView.tag == 901) {
        static NSString *cellStr = @"pageCollectionCell";
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellStr forIndexPath:indexPath];
        
        UIImageView *imageView = (UIImageView *)[cell viewWithTag:101];
        UILabel *label = [(UILabel *)cell viewWithTag:102];
        
        switch (indexPath.row) {
            case 0:
                imageView.image = [UIImage imageNamed:@"home_pm"];
                label.text = NSLocalizedString(@"Convenience services", nil);
                break;
            case 1:
                imageView.image = [UIImage imageNamed:@"home_mz"];
                label.text = NSLocalizedString(@"National specialty", nil);
                break;
            case 2:
                imageView.image = [UIImage imageNamed:@"home_wh"];
                label.text = NSLocalizedString(@"Cultural products title", nil);
                break;
            case 3:
                imageView.image = [UIImage imageNamed:@"home_jc"];
                label.text = NSLocalizedString(@"Season production", nil);
                break;
            case 4:
                imageView.image = [UIImage imageNamed:@"home_dp"];
                label.text = NSLocalizedString(@"beidouself", nil);
                break;
            default:
                break;
        }
        
        return cell;
    } else if (collectionView.tag == 902)  {
        static NSString *cellStr = @"pageHotCell";
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellStr forIndexPath:indexPath];
        UIView *containView = [cell viewWithTag:101];
        containView.layer.borderColor = RGBColor(170, 170, 170).CGColor;
        containView.layer.borderWidth = 0.5;
        // 商品图片
        if (_secondList.count > 0) {
            NSString *goodImageUrl = _secondList[indexPath.row][@"icon"];
            UIImageView *goodImageView = (UIImageView *)[containView viewWithTag:201];
            if (![goodImageUrl isEqual:[NSNull null]]) {
                NSInteger width = goodImageView.width * 2;
                NSInteger height = goodImageView.height * 2;
                goodImageUrl = [NSString stringWithFormat:@"%@?dp_cmd=/imageView2/mode/2/w/%ld/h/%ld/",goodImageUrl,(long)width,(long)height];
                [goodImageView sd_setImageWithURL:[NSURL URLWithString:goodImageUrl] placeholderImage:[UIImage imageNamed:@"image_empty"]];
            }
        } else {
            UIImageView *goodImageView = (UIImageView *)[containView viewWithTag:201];
            goodImageView.image = [UIImage imageNamed:@"image_empty"];
        }
        // 商品名称
        NSString *goodName = _secondList[indexPath.row][@"name"];
        UILabel *goodNameLabel = [containView viewWithTag:202];
        goodNameLabel.text = goodName;
        
        return cell;
    } else {
        static NSString *cellStr = @"pageRecomCell";
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellStr forIndexPath:indexPath];
        UIView *containView = [cell viewWithTag:301];
        containView.layer.borderColor = RGBColor(170, 170, 170).CGColor;
        containView.layer.borderWidth = 0.5;
        if (_thirdList.count > 0) {
            // 商品图片
            NSString *goodImageUrl;
            if (indexPath.row < _thirdList.count) {
                goodImageUrl = _thirdList[indexPath.row][@"icon"];
            }
            UIImageView *goodImageView = (UIImageView *)[cell viewWithTag:101];
            if (![goodImageUrl isEqual:[NSNull null]]) {
                NSInteger width = goodImageView.width * 2;
                NSInteger height = goodImageView.height * 2;
                goodImageUrl = [NSString stringWithFormat:@"%@?dp_cmd=/imageView2/mode/2/w/%ld/h/%ld/",goodImageUrl,(long)width,(long)height];
                [goodImageView sd_setImageWithURL:[NSURL URLWithString:goodImageUrl] placeholderImage:[UIImage imageNamed:@"image_empty"]];
            }
        } else {
            UIImageView *goodImageView = (UIImageView *)[cell viewWithTag:101];
            goodImageView.image = [UIImage imageNamed:@"image_empty"];
        }
        // 商品名称
        UILabel *goodNameLabel = (UILabel *)[cell viewWithTag:102];
        NSString *goodName;
        if (indexPath.row < _thirdList.count) {
            goodName = _thirdList[indexPath.row][@"name"];
        }
        if (![goodName isEqual:[NSNull null]]) {
            goodNameLabel.text = goodName;
        }
        // 商品折扣价格
        UILabel *goodDiscountLabel = (UILabel *)[cell viewWithTag:103];
        // 商品价格
        UILabel *goodPriceLabel = (UILabel *)[cell viewWithTag:104];
        NSString *goodDiscount;
        NSString *goodPrice;
        if (indexPath.row < _thirdList.count) {
            goodDiscount = _thirdList[indexPath.row][@"commodityPrice"][@"discount"];
            goodPrice = _thirdList[indexPath.row][@"commodityPrice"][@"price"];
        }
        if (![goodDiscount isEqual:[NSNull null]] &&
            ![goodPrice isEqual:[NSNull null]]) {
            // 折扣价格
            CGFloat discount = [goodDiscount floatValue];
            CGFloat price = [goodPrice floatValue];
            goodDiscountLabel.text = [NSString stringWithFormat:@"¥ %.2f",price * discount];
            // 价格
            NSString *str = [NSString stringWithFormat:@"¥ %.2f",[goodPrice floatValue]];
            NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
            NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc] initWithString:str attributes:attribtDic];
            goodPriceLabel.attributedText = attribtStr;
//            if (kScreen_Width > 320.0 && kScreen_Width <= 375.0) {
//                for (NSLayoutConstraint* constraint in containView.constraints) {
//                    if (constraint.firstAttribute == NSLayoutAttributeCenterX) {
//                        constraint.constant = -40.0;
//                    }
//                }
//            } else if (kScreen_Width > 375.0) {
//                for (NSLayoutConstraint* constraint in containView.constraints) {
//                    if (constraint.firstAttribute == NSLayoutAttributeCenterX) {
//                        constraint.constant = -45.0;
//                    }
//                }
//            }
            if (discount >= 1.0 || [str isEqualToString:goodDiscountLabel.text]) {
//                for (NSLayoutConstraint* constraint in containView.constraints) {
//                    if (constraint.firstAttribute == NSLayoutAttributeCenterX) {
//                        constraint.constant = 0.0;
//                    }
//                }
                goodPriceLabel.hidden = YES;
            } else {
                goodPriceLabel.hidden = NO;
            }
        }
        UIView *line = [cell viewWithTag:105];
        for (NSLayoutConstraint* constraint in line.constraints) {
            if (constraint.firstAttribute == NSLayoutAttributeHeight) {
                constraint.constant = 0.5;
            }
        }
        line.height = 0.5;
        
        return cell;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width,height;
    if (collectionView.tag == 901) {
        width = kScreen_Width / 5 - 1.0;
        return (CGSize){width,width * fourHeightWidthRatio};
    } else if (collectionView.tag == 902) {
        width = ([UIScreen mainScreen].bounds.size.width) / 3.5;
        height = width * hotHeightWidthRatio;
        return (CGSize){width,height};
    } else if (collectionView.tag == 903) {
        width = ([UIScreen mainScreen].bounds.size.width - 16.0 - 12.0) / 3;
        if (kScreen_Width <= 320.0) {
            _recomHeightWidthRatio = 1.3675;
        } else if (kScreen_Width > 320.0 && kScreen_Width <= 375.0) {
            _recomHeightWidthRatio = 1.3675;
        } else {
            _recomHeightWidthRatio = 1.3675;
        }
        height = width * _recomHeightWidthRatio;
        return (CGSize){width,height};
    }
    return (CGSize){width,width};
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView.tag == 901) {
        UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        BDTypeViewController *vc = [stroyboard instantiateViewControllerWithIdentifier:@"TypeStoryboardID"];
        vc.showBackButton = YES;
        if (indexPath.row == 0) {
            if ([[BDAccountManagerModel shareInstance].inBoundary isEqualToString:@"yes"]) {
                NSArray *firstArr = @[@"每日活动",@"民贸超市",@"果蔬生鲜",@"凉卤",@"速食",@"糕点",@"藏式简餐",@"派对",@"其他"];
                NSArray *secondArr = @[@[]
                                       ,@[@"食品",@"土特产",@"百货",@"针织品",@"日常洗化",@"季节商品"]
                                       ,@[@"水果",@"蔬菜",@"其他"]
                                       ,@[@"凉卤"]
                                       ,@[@"甜品",@"饮品",@"简餐",@"其他"]
                                       ,@[@"糕点"]
                                       ,@[@"藏式简餐"]
                                       ,@[@"鲜花",@"道具",@"其他"]
                                       ,@[@"其他"]];
                NSArray *thirddArr = @[@[@"烟酒茶",@"奶饮",@"休闲食品",@"方便食品",@"进口食品",@"米面调味",@"冷冻冷藏"],
                                       @[@"土特产"],
                                       @[@"纸制品",@"厨具用品",@"家电",@"家居用品",@"文化用品"],
                                       @[@"毛巾",@"内衣内裤",@"袜子",@"床上用品"],
                                       @[@"家居清洁",@"护肤品",@"美发护发",@"口腔护理"],
                                       @[@"季节商品"]];
                vc.title = @"便民服务";
                vc.firstArr = firstArr;
                vc.secondArr = secondArr;
                vc.thirdArr = thirddArr;
                [self.navigationController pushViewController:vc animated:YES];
            } else if ([[BDAccountManagerModel shareInstance].inBoundary isEqualToString:@"no"])  {
                [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Your area does not support convenience services", nil)];
            } else if ([[BDAccountManagerModel shareInstance].inBoundary isEqualToString:@"doing"]) {
                [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"In positioning", nil)];
            } else if ([[BDAccountManagerModel shareInstance].inBoundary isEqualToString:@"fail"]) {
                [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"seek failed", nil)];
            }
        } else if (indexPath.row == 1) {
            NSArray *firstArr = @[@"药材",@"食品",@"服饰",@"手工艺",@"其他"];
            NSArray *secondArr = @[@[@"药材"],
                                   @[@"菌类",@"肉类",@"保健品",@"冷冻生鲜",@"干货",@"特色饮品",@"其他"],
                                   @[@"包类",@"鞋服",@"首饰",@"配件",@"户外",@"生活",@"其他"],
                                   @[@"手工艺"],
                                   @[@"其他"]];
            vc.title = @"民族特色";
            vc.firstArr = firstArr;
            vc.secondArr = secondArr;
            [self.navigationController pushViewController:vc animated:YES];
        } else if (indexPath.row == 2) {
            NSArray *firstArr = @[@"图书",@"手工艺",@"服饰",@"其他"];
            NSArray *secondArr = @[@[@"图书"],@[@"手工艺"],@[@"包类",@"鞋服",@"首饰",@"配件",@"户外",@"生活",@"其他"],@[@"其他"]];
            vc.title = @"文化产品";
            vc.firstArr = firstArr;
            vc.secondArr = secondArr;
            [self.navigationController pushViewController:vc animated:YES];
        } else if (indexPath.row == 3) {
            NSArray *firstArr = @[@"生鲜",@"干货",@"其他"];
            NSArray *secondArr = @[@[@"生鲜"],@[@"干货"],@[@"其他"]];
            vc.title = @"季产";
            vc.firstArr = firstArr;
            vc.secondArr = secondArr;
            [self.navigationController pushViewController:vc animated:YES];
        } else if (indexPath.row == 4) {
            UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"ThirdStoryboard" bundle:[NSBundle mainBundle]];
            BDSelfSupportHomeViewController *detailVC = [stroyboard instantiateViewControllerWithIdentifier:@"selfSupportHomeStoryboardID"];
            [self.navigationController pushViewController:detailVC animated:YES];
        }
    } else if (collectionView.tag == 902) {
        if (_secondList.count > 0) {
            NSDictionary *goodDic = _secondList[indexPath.row];
            NSString *commodityId = goodDic[@"commodityId"];
            UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"SecondStoryboard" bundle:[NSBundle mainBundle]];
            BDGoodDetailViewController *detailVC = [stroyboard instantiateViewControllerWithIdentifier:@"goodDetailStoryboardID"];
            detailVC.commodityId = commodityId;
            detailVC.isFromHomePage = YES;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
    } else if (collectionView.tag == 903) {
        if (_thirdList.count > 0) {
            NSDictionary *goodDic = _thirdList[indexPath.row];
            NSString *commodityId = goodDic[@"commodityId"];
            UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"SecondStoryboard" bundle:[NSBundle mainBundle]];
            BDGoodDetailViewController *detailVC = [stroyboard instantiateViewControllerWithIdentifier:@"goodDetailStoryboardID"];
            detailVC.commodityId = commodityId;
            detailVC.isFromHomePage = YES;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
    }
}

#pragma mark - SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    if (_firstList.count > 0) {
        NSString *commodityId = _firstList[index][@"commodityId"];
        if ([commodityId isEqual:[NSNull null]] ||
            commodityId != nil) {
            UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"SecondStoryboard" bundle:[NSBundle mainBundle]];
            BDGoodDetailViewController *detailVC = [stroyboard instantiateViewControllerWithIdentifier:@"goodDetailStoryboardID"];
            detailVC.commodityId = commodityId;
            detailVC.isFromHomePage = YES;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
    }
}

#pragma mark UITabBarControllerDelegate

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    BDNavigationController *nav_vc = (BDNavigationController *)viewController;
    if ([nav_vc.topViewController isKindOfClass:[BDBeidouViewController class]]) {// 点击背兜
        if ([BDAccountManagerModel shareInstance].login) {// 已登录,检查是否登录超时
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:@""];
            
            tabBarController.selectedIndex = _selectControllerIndex;
            
            NSString *url = [NSString stringWithFormat:@"%@%@?userId=%@&pageSize=%@&currentPage=%@",
                             [BDNetworking shareInstance].baseUrl,
                             Cart,
                             [BDAccountManagerModel shareInstance].userId,
                             @(1),
                             @(1)];
            [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
                [hud hideAfterDelay:0.2];
                if (error != nil) {
                    NSLog(@"获取背兜数据失败:%@",error);
                    if ([[error localizedDescription] isEqualToString:@"登录超时"] && error.code == 401) {
                        // 清除webViw cookie
                        NSHTTPCookie *cookie;
                        NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
                        for (cookie in [storage cookies])
                        {
                            [storage deleteCookie:cookie];
                        }
                        [BDAccountManagerModel shareInstance].authorization = @"";
                        [BDAccountManagerModel shareInstance].login = NO;
                        
                        UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
                        BDNavigationController *nav_vc = [stroyboard instantiateViewControllerWithIdentifier:@"navLoginStoryboardID"];
                        BDLoginTableViewController *vc = (BDLoginTableViewController *)nav_vc.topViewController;
                        vc.showShopcart = YES;
                        vc.tabBarController = tabBarController;
                        [self presentViewController:nav_vc animated:YES completion:nil];
                    } else {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            tabBarController.selectedIndex = 3;
                        });
                    }
                } else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        tabBarController.selectedIndex = 3;
                    });
                }
            }];
            
        } else if (![BDAccountManagerModel shareInstance].login) {// 未登录
            tabBarController.selectedIndex = _selectControllerIndex;
            UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
            BDNavigationController *nav_vc = [stroyboard instantiateViewControllerWithIdentifier:@"navLoginStoryboardID"];
            BDLoginTableViewController *vc = (BDLoginTableViewController *)nav_vc.topViewController;
            vc.showShopcart = YES;
            vc.tabBarController = tabBarController;
            [self presentViewController:nav_vc animated:YES completion:nil];
        }
    } else {
        _selectControllerIndex = tabBarController.selectedIndex;
    }
}

#pragma mark IBActions

- (IBAction)ganziButtonPressed:(UIButton *)sender {
    UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"ThirdStoryboard" bundle:[NSBundle mainBundle]];
    BDGanziHomeViewController *detailVC = [stroyboard instantiateViewControllerWithIdentifier:@"ganziHomeStoryboardID"];
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (IBAction)minmaoButtonPressed:(UIButton *)sender {
    UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"ThirdStoryboard" bundle:[NSBundle mainBundle]];
    BDMinmaoHomeViewController *detailVC = [stroyboard instantiateViewControllerWithIdentifier:@"minmaoHomeStoryboardID"];
    [self.navigationController pushViewController:detailVC animated:YES];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
